package com.mytinyRPC.framework;



import com.mytinyRPC.framework.loadBalance.Impl.SmoothWeightedRandom;
import com.mytinyRPC.framework.loadBalance.LoadBalance;
import com.mytinyRPC.protocol.http.HttpClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory {

    private static LoadBalance loadBalance;
    static {
        loadBalance=new SmoothWeightedRandom();
    }

    public static <T> T getProxy(final Class interfaceClass){
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //用的是jdk11中标准化的httpClient
                HttpClient httpClient=new HttpClient();
                Invocation invocation=new Invocation(interfaceClass.getName(), method.getName(),method.getParameterTypes(),args);
                //负载均衡选择服务器
                URL url=ProxyFactory.loadBalance.loadBalance(interfaceClass.getName());
                String result=httpClient.send(url.getHostname(),url.getPort(),invocation);
                return result;
            }
        });

    }
}
